#include "ringQueue.hpp"
#include "Thread.hpp"
#include "Task.hpp"
#include <string>
#include <vector>
#include <unistd.h>
#include <ctime>

using namespace ThreadModule;
using namespace std;
using ringqueue_t = ringQueue<Task>;

void Consumer(ringqueue_t &rq, string name)
{
    while (true)
    {
        sleep(1);
        Task t;
        rq.Pop(&t);
        cout << "Consumer handler task:" << "[" << name << "]" << endl;
        t();
    }
}

void Productor(ringqueue_t &rq, string name)
{
    while (true)
    {
        rq.Enqueue(Download);
        cout << "Productor :" << "[" << name << "]" << endl;
    }
}

void InitComm(vector<Thread<ringqueue_t>> *threads, int num, ringqueue_t &rq, func_t<ringqueue_t> func, const std::string &who)
{
    for (int i = 0; i < num; i++)
    {
        string name = "thread-" + to_string(i + 1) + "-" + who;
        threads->emplace_back(func, rq, name);
    }
}

void InitConsumer(vector<Thread<ringqueue_t>> *threads, int num, ringqueue_t &rq)
{
    InitComm(threads, num, rq, Consumer, "consumer");
}

void InitProductor(vector<Thread<ringqueue_t>> *threads, int num, ringqueue_t &rq)
{
    InitComm(threads, num, rq, Productor, "productor");
}

void WaitAllThread(vector<Thread<ringqueue_t>> &threads)
{
    for (auto &thread : threads)
    {
        thread.Join();
    }
}

void StartAll(vector<Thread<ringqueue_t>> &threads)
{
    for (auto &thread : threads)
    {
        cout << "start: " << thread.name() << endl;
        thread.Start();
    }
}

int main()
{
    ringqueue_t *rq = new ringqueue_t(10);
    vector<Thread<ringqueue_t>> threads;

    InitProductor(&threads, 1, *rq);
    InitConsumer(&threads, 1, *rq);

    StartAll(threads);
    WaitAllThread(threads);

    return 0;
}